package com.haiyi.software.app.basic;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

public abstract class RegisterSexActivityBasic extends ActivityBasic {

	private final String str_requestName = "updRegUser.php";

	protected String string;

	public void regSex(String uid, String uname, String pwd, String guid,
			String usex, String username) {

		Map<String, Object> validator = new HashMap<String, Object>();

		validator.put("uid", uid);
		validator.put("uname", uname);
		validator.put("pwd", pwd);
		validator.put("uguid", guid);

		Map<String, Object> body = new HashMap<String, Object>();
		body.put("usex", usex);
		body.put("username", username);

		Map<String, Object> args = new HashMap<String, Object>();
		args.put("validator", validator);
		args.put("body", body);

		Gson gson = new Gson();
		String s = gson.toJson(args);

		Log.i(str_requestName, s);

		requestNetworkData(s);

	}

	public synchronized void requestNetworkData(Object... args) {

		if (!isWork) {

			isWork = true;

			String str_requestURL = str_server + str_requestName;

			AsyncHttpClient client = new AsyncHttpClient();

			RequestParams params = new RequestParams();

			params.add("args", args[0].toString());

			client.post(str_requestURL, params, responseHandler);
		}

	}

	private ResponseHandlerInterface responseHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {
			// TODO 自动生成的方法存根
			isWork = false;

			try {

				String str_jsonReturn = new String(responseBody, "UTF-8");
				Log.i(str_requestName, str_jsonReturn);
				JsonParser parser = new JsonParser();

				JsonObject jsonObj_return = parser.parse(str_jsonReturn)
						.getAsJsonObject();

				requestFinish(jsonObj_return);

			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				requestError();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根
			isWork = false;
			requestError();
		}
	};

}
